package com.ls.mysql.filter;

import com.alibaba.fastjson.JSONObject;
import com.ls.mysql.util.JWTUtil;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

public class CToken implements HandlerInterceptor {
    /*
    对指定接口请求，拦截无效令牌
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 修正拦截器返回给客户端的信息编码
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        int statusCode = -4;
        String msg = "身份信息验证已过期，请重新登录";
        JSONObject json = new JSONObject();
        String token = request.getHeader("userToken");
        if (token != null) {
            boolean verify = JWTUtil.verify(token);
            if (verify) {
                return true;
            }
        }
        json.put("statusCode", statusCode);
        json.put("msg", msg);
        response.setContentType("application/json;charset=utf-8");
        PrintWriter pw = response.getWriter();
        pw.write(json.toJSONString());
        pw.flush();
        pw.close();
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
